import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs';
import {RequestService} from '../../services/request.service';
import {filter, map} from 'rxjs/operators';

@Component({
  selector: 'app-rxjs',
  templateUrl: './rxjs.component.html',
  styleUrls: ['./rxjs.component.scss']
})
export class RxjsComponent implements OnInit {

  constructor(public req: RequestService) {
  }

  ngOnInit(): void {
    let promise = this.req.getDataByPromise();
    promise.then((data) => {
      console.log(data);
    });

    let observable = this.req.getDataByRxjs();
    let o = observable.subscribe((data) => {
      console.log(data);
    });
    setTimeout(() => {
      o.unsubscribe(); // 取消订阅
    }, 1000);
    // filter使用
    // let observable2 = this.req.getIntervalDataByRxjs();
    // observable2.pipe(filter((value:any) => {
    //   if (value % 2 == 0) {
    //     return true;
    //   }
    // })).subscribe((data) => {
    //   console.log(data);
    // });
    //map 使用
    let observable2 = this.req.getIntervalDataByRxjs();
    observable2.pipe(map((value: any) => {
      return value * value;
    })).subscribe((data) => {
      console.log(data);
    });
  }
}
